package top.lingkang.websocketlivechrome.ws;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理消息的handler
 * 在netty中，是用于为websocket专门处理文本的 对象，frames是消息的载体
 */
public class NettyHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    //用于记录和管理所有客户端的channel
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static Map<String, String> map = new HashMap<>();

    /**
     * http升级websocket前进行鉴权
     **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame msg) throws Exception {
        if (msg!=null){
            System.out.println(msg.getClass());
            System.out.println(msg.toString());
        }
    }

    /**
     * 当客户端连接到服务端后（打开链接）
     * 获取客户端的channel，并且放到channelGroup中去进行管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    /**
     * 连接断开，触发移除
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开，他的短id为:" + ctx.channel().id().asShortText());
        clients.remove(ctx.channel());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue().equals(ctx.channel().id().asShortText())) {
                map.remove(entry.getKey());
                break;
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
